package com.example.jetgege.smsdemo;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by jetgege on 2017/2/26.
 */

public class MyService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d("TAG2","test service");
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");//定义广播接收器类别——短信接收器
        filter.setPriority(Integer.MAX_VALUE);//方法设置该广播接收器优先级，Integer 最大值为最高优先级。
        registerReceiver(new SMSReceiver(), filter);
    }



    class  SMSReceiver extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Object[] pdusObjects = (Object[]) bundle.get("pdus");
                SmsMessage[] messages = new SmsMessage[pdusObjects.length];
                for (int i = 0; i < pdusObjects.length; i++) {
                    messages[i] = SmsMessage
                            .createFromPdu((byte[]) pdusObjects[i]);
                }
                for (SmsMessage message : messages) {

                    Toast.makeText(context,"来信号码：" +message.getDisplayOriginatingAddress()+"\n短信内容："+message.getDisplayMessageBody(),Toast.LENGTH_LONG).show();

                    Log.d("onReceive   ==","来信号码：" +message.getDisplayOriginatingAddress()+"\n短信内容："+message.getDisplayMessageBody());
                }
            }
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
